<template>
	<div class="home-container">
		<el-card shadow="hover" class="mb10">
			<el-form :inline="true" :model="search">
				<el-form-item label="选择用户" prop="userId">
					<el-select v-model="search.userId" filterable remote 
						@change="handleCrmUserChange"
						@click="loadCrmUserData()"
						:remote-method="loadCrmUserData" placeholder="请选择统计用户" clearable class="w100">
						<el-option 
							v-for="item in users"
							:key="item.id"
							:label="item.userName"
							:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="选择部门" prop="deptId">
					<el-cascader
						@change="handleCrmDeptChange"
						placeholder="请选择统计部门"
						v-model="search.deptId"
						:options="depts"
						:props="{expandTrigger: 'hover', emitPath: false, checkStrictly: true, value: 'id', label: 'deptName', children: 'children' }"
						class="w100"
						filterable
						clearable>
					</el-cascader>
				</el-form-item>
				<el-form-item>
                    <el-date-picker type="daterange" align="right" 
						@change="handleDateChange"
						v-model="dateData.value" 
						:shortcuts="dateData.shortcuts" 
                        unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                </el-form-item>
			</el-form>
		</el-card>
		<el-row :gutter="15">
			<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb15" v-auth="'crm:home:contract'">
				<el-card shadow="hover" header="合同增长趋势图">
					<div style="height: 300px" ref="contractCountInfoRef"></div>
				</el-card>
			</el-col>
			<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb15" v-auth="'crm:home:project'">
				<el-card shadow="hover" header="项目月度情况">
					<div style="height: 300px" ref="projectStatusRef"></div>
				</el-card>
			</el-col>
			<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb15" v-auth="'crm:home:customer'">
				<el-card shadow="hover" header="客户/企业增长趋势图">
					<div style="height: 300px" ref="customerEnterpriseInfoRef"></div>
				</el-card>
			</el-col>
			<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb15" v-auth="'crm:home:receivable'">
				<el-card shadow="hover" header="收支月度情况">
					<div style="height: 300px" ref="monthAmountInfoRef"></div>
				</el-card>
			</el-col>
		</el-row>
	</div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted, nextTick, watch, onActivated } from 'vue';
import * as echarts from 'echarts';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo';
import { useTagsViewRoutes } from '/@/stores/tagsViewRoutes';
import { formatDate, getDateRangeShortcuts } from '/@/utils/formatTime';
import { topCardItemList, contractCountInfoOption, customerEnterpriseInfoOption, projectStatusOption, monthAmountInfoOption } from './mock';
import { countCrmContractByDay, countCrmCustomerByDay, countCrmEnterpriseByDay, countCrmProjectStatusByDay, countCrmAmountByMonth } from '/@/api/crm/home/index';
import { getCrmUserList } from '/@/api/crm/user/index';
import { getCrmDeptList } from '/@/api/crm/dept/index';
import { lineToTreeData } from '/@/utils/commonFunction';
export default {
	name: 'home',
	components: { },
	setup() {
		const stores = useUserInfo();
		const storesTagsViewRoutes = useTagsViewRoutes();
		const { isTagsViewCurrenFull } = storeToRefs(storesTagsViewRoutes);
		const contractCountInfoRef = ref();
		const projectStatusRef = ref();
		const customerEnterpriseInfoRef = ref();
		const monthAmountInfoRef = ref();
		const state = reactive({
			topCardItemList,
			myCharts: [],
			users: [],
            depts: [],
			search: {
				userId: stores.userInfos.id,
				deptId: undefined,
				startDate: undefined,
				endDate: undefined,
			},
			dateData: {
                value: [],
                shortcuts: getDateRangeShortcuts()
            },
		});
		// 合同日增长详情
		const initContractCountInfo = async () => {
			const option = contractCountInfoOption;
			await countCrmContractByDay({
				userId: state.search.userId, 
				deptId: state.search.deptId,
				startDate: state.search.startDate,
				endDate: state.search.endDate,
			}).then(res => {
				if(res.code == 0){
					option.xAxis.data = res.data[0];
					option.series[0].data = res.data[1];
				}
			})
			const myChart = echarts.init(contractCountInfoRef.value);
			myChart.setOption(option);
			state.myCharts.push(myChart);
		};
		// 项目完成情况
		const initProjectStatusInfo = async () => {
			const option = projectStatusOption;
			await countCrmProjectStatusByDay({
				userId: state.search.userId, 
				deptId: state.search.deptId,
				startDate: state.search.startDate,
				endDate: state.search.endDate,
			}).then(res => {
				if(res.code == 0){
					option.series[0].data = res.data;
				}
			})
			const myChart = echarts.init(projectStatusRef.value);
			myChart.setOption(option);
			state.myCharts.push(myChart);
		};
		// 客户企业日增长详情
		const initCustomerEnterpriseInfo = async () => {
			const option = customerEnterpriseInfoOption;
			await countCrmCustomerByDay({
				userId: state.search.userId, 
				deptId: state.search.deptId,
				startDate: state.search.startDate,
				endDate: state.search.endDate,
			}).then(res => {
				if(res.code == 0){
					option.xAxis.data = res.data[0];
					option.series[0].data = res.data[1];
				}
			})
			await countCrmEnterpriseByDay({
				status: 1, userId: 
				state.search.userId, 
				deptId: state.search.deptId,
				startDate: state.search.startDate,
				endDate: state.search.endDate,
			}).then(res => {
				if(res.code == 0){
					option.xAxis.data = res.data[0];
					option.series[1].data = res.data[1];
				}
			})
			const myChart = echarts.init(customerEnterpriseInfoRef.value);
			myChart.setOption(option);
			state.myCharts.push(myChart);
		};
		// 月度收支情况
		const initMonthAmountInfo = async () => {
			const option = monthAmountInfoOption;
			await countCrmAmountByMonth({
				userId: state.search.userId, 
				deptId: state.search.deptId,
				startDate: state.search.startDate,
				endDate: state.search.endDate,
			}).then(res => {
				if(res.code == 0){
					option.series[0].data = res.data?.expense[1];
					option.series[1].data = res.data?.receivable[1];
					option.series[2].data = res.data?.contract[1];
					option.xAxis.data = res.data?.contract[0];
				}
			})
			const myChart = echarts.init(monthAmountInfoRef.value);
			myChart.setOption(option);
			state.myCharts.push(myChart);
		}
		// 批量设置 echarts resize
		const initEchartsResizeFun = () => {
			nextTick(() => {
				for (let i = 0; i < state.myCharts.length; i++) {
					state.myCharts[i].resize();
				}
			});
		};
		// 批量设置 echarts resize
		const initEchartsResize = () => {
			window.addEventListener('resize', initEchartsResizeFun);
		};
		const initRenderHomeView = () => {
			if(stores.userInfos.authBtnList.some((v: string) => v === 'crm:home:contract')){
				initContractCountInfo();
			}
			if(stores.userInfos.authBtnList.some((v: string) => v === 'crm:home:project')){
				initProjectStatusInfo();
			}
			if(stores.userInfos.authBtnList.some((v: string) => v === 'crm:home:customer')){
				initCustomerEnterpriseInfo();
			}
			if(stores.userInfos.authBtnList.some((v: string) => v === 'crm:home:receivable')){
				initMonthAmountInfo();
			}
			initEchartsResize();
		};
		// 由于页面缓存原因，keep-alive
		onActivated(() => {
			initEchartsResizeFun();
		});
		// 监听 vuex 中的 tagsview 开启全屏变化，重新 resize 图表，防止不出现/大小不变等
		watch(
			() => isTagsViewCurrenFull.value,
			() => {
				initEchartsResizeFun();
			}
		);
		// 页面加载时
		onMounted(() => {
			initRenderHomeView();
			loadCrmDeptData();
			state.users = [{id: stores.userInfos.id, userName: stores.userInfos.userName}];
		});

		const loadCrmUserData = (query?: string) => {
            if(query == '') return;
            getCrmUserList({userName: query}).then((res) => {
                if(res.code == 0){
                    state.users = res.data;
                }
            });
        }

		const handleCrmUserChange = (id: string) => {
            initRenderHomeView();
        }

		const loadCrmDeptData = () => {
            getCrmDeptList().then((res) => {
                if(res.code == 0 && res.data?.length > 0){
                    state.depts = lineToTreeData(res.data);
                }
            });
        }

		const handleCrmDeptChange = (id: string) => {
            initRenderHomeView();
        }

		const handleDateChange = (value: any) => {
			if(state.dateData.value.length == 2){
                state.search.startDate = formatDate(state.dateData.value[0], 'yyyy-MM-dd');
                state.search.endDate = formatDate(state.dateData.value[1], 'yyyy-MM-dd');
            }else{
				state.search.startDate = undefined;
				state.search.endDate = undefined;
			}
			initRenderHomeView();
		}

		return {
			contractCountInfoRef,
			projectStatusRef,
			customerEnterpriseInfoRef,
			monthAmountInfoRef,
			loadCrmUserData,
			loadCrmDeptData,
			handleCrmUserChange,
			handleCrmDeptChange,
			handleDateChange,
			...toRefs(state),
		};
	},
};
</script>

<style scoped lang="scss">
.home-container {
	overflow-x: hidden;
	.home-card-item {
		width: 100%;
		height: 103px;
		background: var(--el-text-color-secondary);
		border-radius: 4px;
		transition: all ease 0.3s;
		&:hover {
			box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
			transition: all ease 0.3s;
		}
	}
	.home-card-item-box {
		display: flex;
		align-items: center;
		position: relative;
		overflow: hidden;
		&:hover {
			i {
				right: 0px !important;
				bottom: 0px !important;
				transition: all ease 0.3s;
			}
		}
		i {
			position: absolute;
			right: -10px;
			bottom: -10px;
			font-size: 70px;
			transform: rotate(-30deg);
			transition: all ease 0.3s;
		}
		.home-card-item-flex {
			padding: 0 20px;
			color: var(--color-whites);
			.home-card-item-title,
			.home-card-item-tip {
				font-size: 13px;
				color: var(--el-color-white);
			}
			.home-card-item-title-num {
				font-size: 18px;
				color: var(--el-color-white);
			}
			.home-card-item-tip-num {
				font-size: 13px;
				color: var(--el-color-white);
			}
		}
	}
	.home-item-third-app {
		display: inline-block;
		width: 135px;
		padding: 5px;
		cursor: pointer;
		text-align: center;
		margin-right: 10px;
		&-img {
			height: 65px;
		}
		&-text {
			line-height: 30px;
			overflow: hidden;
			text-overflow: ellipsis;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 1;
		}
	}
	.home-card-first {
		background: var(--el-color-white);
		border: 1px solid var(--el-border-color-light, #ebeef5);
		display: flex;
		align-items: center;
		img {
			width: 60px;
			height: 60px;
			border-radius: 100%;
			border: 2px solid var(--color-primary-light-5);
		}
		.home-card-first-right {
			flex: 1;
			display: flex;
			flex-direction: column;
			.home-card-first-right-title {
				color: var(--el-color-black);
			}
			.home-card-first-right-msg {
				font-size: 13px;
				color: var(--el-text-color-secondary);
			}
		}
	}
	.home-monitor {
		height: 200px;
		.flex-warp-item {
			width: 50%;
			height: 100px;
			display: flex;
			.flex-warp-item-box {
				margin: auto;
				height: auto;
				text-align: center;
				color: var(--el-text-color-primary);
			}
		}
	}
	.home-warning-card {
		height: 292px;
		:deep(.el-card) {
			height: 100%;
		}
	}
	.home-dynamic {
		height: 200px;
		.home-dynamic-item {
			display: flex;
			width: 100%;
			height: 60px;
			overflow: hidden;
			&:first-of-type {
				.home-dynamic-item-line {
					i {
						color: orange !important;
					}
				}
			}
			.home-dynamic-item-left {
				text-align: right;
				.home-dynamic-item-left-time1 {
				}
				.home-dynamic-item-left-time2 {
					font-size: 13px;
					color: var(--el-text-color-secondary);
				}
			}
			.home-dynamic-item-line {
				height: 60px;
				border-right: 2px dashed var(--el-border-color-light, #ebeef5);
				margin: 0 20px;
				position: relative;
				i {
					color: var(--color-primary);
					font-size: 12px;
					position: absolute;
					top: 1px;
					left: -6px;
					transform: rotate(46deg);
					background: var(--el-color-white);
				}
			}
			.home-dynamic-item-right {
				flex: 1;
				.home-dynamic-item-right-title {
					i {
						margin-right: 5px;
						border: 1px solid var(--el-border-color-light, #ebeef5);
						width: 20px;
						height: 20px;
						border-radius: 100%;
						padding: 3px 2px 2px;
						text-align: center;
						color: var(--color-primary);
					}
				}
				.home-dynamic-item-right-label {
					font-size: 13px;
					color: var(--el-text-color-secondary);
				}
			}
		}
	}
}
</style>
